//
//  String+Extension.swift
//  YJWeiBo
//
//  Created by Jim1024 on 2017/1/17.
//  Copyright © 2017年 Jim1024. All rights reserved.
//

import Foundation

/*
 正则表达式:
 pattern: 规则
 .: 表示匹配任意一个字符,换行除外
 *: 表示匹配任意多的字符
 ?: 表示尽可能少的匹配
 (): 捕获()里面的内容作为匹配结果
 
 options: 选项
 NSRegularExpressionOptions.DotMatchesLineSeparators: .可以匹配换行
 
 */

extension String {
    func sinaSource() -> String {
        // 从字符串里面截取 iPhone 6
        // <a href=\"http://weibo.com/\" rel=\"nofollow\">微博 weibo.com</a>
        // "<a href=\"http://app.weibo.com/t/feed/3o33sO\" rel=\"nofollow\">iPhone 6</a>nofollow\">iPhone 6</a>"
        let pattern = ">(.*?)<"
        guard let regular = try? NSRegularExpression(pattern: pattern, options: .dotMatchesLineSeparators) else {
            return "未知来源"
        }
        let result = regular.firstMatch(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: self.characters.count))
        
        // 配到的的范围数量
        let count = result?.numberOfRanges ?? 0
        if count > 1 {
            let range = result!.rangeAt(1)
            return (self as NSString).substring(with: range)
        }
        return "未知来源"
    }
}
